export default {
	namespaced: true,
	state: () => ({
		// 购物车数组
		// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
		cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
	}),
	mutations: {
		// 添加购物车
		addToCart(state, goods) {
			const findResult = state.cart.find((x) => x.goods_id === goods.goods_id);
			console.log(findResult);
			if (!findResult) {
				state.cart.push(goods);
			} else {
				findResult.goods_count++;
			}
			console.log(state.cart);
			// 通过 commit 方法，调用 m_cart 命名空间下的 saveToStorage 方法
			this.commit('m_cart/saveToStorage');
		},
		// 存储购物车数据
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart));
		},
		// 更新购物车商品的勾选状态
		updateGoodsState(state, goods) {
			const findResult = state.cart.find((item) => item.goods_id === goods.goods_id);
			// 存在商品
			if (findResult) {
				findResult.goods_state = goods.goods_state;
				this.commit('m_cart/saveToStorage');
			}
		},
		// 更新购物车商品数量
		updateGoodsCount(state, goods) {
			const findResult = state.cart.find((item) => item.goods_id === goods.goods_id);
			// 存在商品
			if (findResult) {
				findResult.goods_count = goods.goods_count;
				this.commit('m_cart/saveToStorage');
			}
		},
		// 删除购物车商品
		removeGoodsById(state, goods_id) {
			state.cart = state.cart.filter((item) => item.goods_id !== goods_id);
			this.commit('m_cart/saveToStorage');
		},
		// 更新所有商品的勾选状态
		updateAllGoodsState(state, newState) {
			// 循环更新购物车中每件商品的勾选状态
			state.cart.forEach((item) => (item.goods_state = newState));
			this.commit('m_cart/saveToStorage');
		},
	},

	getters: {
		// 统计购物车数量
		total(state) {
			let sum = 0;
			state.cart.forEach((item) => (sum += item.goods_count));
			return sum;
			// 使用reduce
			// return state.cart.reduce((total, item) => total += item.goods_count, 0)
		},
		// 统计购物车勾选商品数量
		checkedCount(state) {
			return state.cart
				.filter((item) => item.goods_state)
				.reduce((total, i) => (total += i.goods_count), 0);
		},
		// 统计已勾选总金额
		checkedGoodsAmount(state) {
			return state.cart
				.filter((item) => item.goods_state)
				.reduce((total, i) => (total += i.goods_price * i.goods_count), 0)
				.toFixed(2);
		},
	},
};
